package com.example.mvc.service;

import com.example.mvc.bean.User;
import com.example.mvc.mapper.BrandMapper;
import com.example.mvc.mapper.UserMapper;
import com.example.mvc.utils.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

public class UserService {
    SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();

    //登录功能
    public User login(String username,String password){
        //获取SqlSession
        SqlSession sqlSession = factory.openSession();
        //获取BrandMapper
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //调用方法
        User user = mapper.select(username, password);

        return  user;

    }


    //注册
    public  boolean register(User user){
        //获取SqlSession
        SqlSession sqlSession = factory.openSession();
        //获取BrandMapper
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //根据用户名查询用户是否已经存在
        User u = mapper.selectByUsername(user.getUsername());
        if (u==null){//为空说明用户不存在，可以注册
            //调用mapper的插入实现用户注册
            mapper.add(user);
            //提交
            sqlSession.commit();
        }
        //资源释放
        sqlSession.close();
        return u==null;

    }

}
